package com.fhz.fengmvvm.test;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.fhz.fengmvvm.R;
import com.fhz.fengmvvm.databinding.ActivityMain2Binding;
import com.fhz.fengmvvm.user.Food;
import com.fhz.fhzutil.StringUtils;

/**
 * @author: fhz
 * @describe:
 * @date: 2021-11-9 11:13:41
 */

public class Main2Activity extends AppCompatActivity {
    private TextView tv;
    private Button btn;
//    private int index = 0;
    private MyViewModel myViewModel;

    private ActivityMain2Binding activityMain2Binding;
    private SharedPreferences sharedPreferences;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main2);

        activityMain2Binding = DataBindingUtil.setContentView(this, R.layout.activity_main2);
//        Food food = new Food();
//        food.setRet(123);
//
//        tv = (TextView) findViewById(R.id.tv);
//        btn = (Button) findViewById(R.id.btn);




        sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);

        int core = sharedPreferences.getInt("core", 0);

//        int key = savedInstanceState.getInt("key",10);
//         myViewModel = new MyViewModel();//生命周期不对

        myViewModel = ViewModelProviders.of(this,new MyViewModelFactory(core)).get(MyViewModel.class);

        getLifecycle().addObserver(myViewModel);
        myViewModel.getFood();

        myViewModel.foodMutableLiveData.observe(this, new Observer<Food>() {
            @Override
            public void onChanged(Food food) {
                activityMain2Binding.setFood(food);
            }
        });


        this.myViewModel.mutableLiveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                activityMain2Binding.tv.setText(String.valueOf(Main2Activity.this.myViewModel.mutableLiveData.getValue()));
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putInt("core",myViewModel.mutableLiveData.getValue());
        edit.commit();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    public void btn(View view) {
        myViewModel.add();
    }
}
